package com.ruoyi.yl.process;


import com.ruoyi.common.domain.body.WeChatLoginBody;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.util.Base64;

/**
 * 微信登录服务
 */
public interface WeChatLoginProcess {

    /**
     * 修改用户信息
     * @param nickName
     * @param phoneNumber
     * @param avatarUrl
     */
    void updateUserInfo(String nickName, String phoneNumber, String avatarUrl);

    record WxSessionResult (String openId, String wxSessionKey,String token) {}

    /**
     * 微信用户登陆
     * @param body body
     * @return WxSessionResult
     */
    WxSessionResult login(WeChatLoginBody body);



     default String decrypt(String encryptedData, String sessionKey, String iv) {
        try {
            byte[] dataByte = Base64.getDecoder().decode(encryptedData);
            byte[] keyByte = Base64.getDecoder().decode(sessionKey);
            byte[] ivByte = Base64.getDecoder().decode(iv);

            // 确保 key 是 16 的倍数
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }

            // 设置解密参数
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);

            byte[] resultByte = cipher.doFinal(dataByte);
            return new String(resultByte, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("微信数据解密失败", e);
        }
    }
}
